<template>
    <view class="wanderReceive">
        <fl-search @searchCon="searchCon" />
        <view class="bottom_container">
            <scroll-view scroll-y class="left_scroll">
                <view v-for="(ele, index) in doc" :key="index"
                    :class="acIndex === index ? 'clickAct scroll_item' : 'scroll_item'" @tap="clickItem(index)">
                    <text>{{ ele.orgName }}</text>
                    <text v-show="acIndex === index" class="line"></text>
                </view>
            </scroll-view>
            <scroll-view v-show="index === acIndex" scroll-y class="right_scroll" v-for="(ele, index) in doc" :key="ele.id">
                <view class="user_box">
                    <u-checkbox-group @change="handleCheckedAll">
                        <view @tap="handleCheckedAll" class="checkAll">
                            <text :style="{ color: ele.isCheckedAll ? '#2362A6' : '#333' }">全选</text>
                            <u-checkbox activeColor="#2362A6" shape="circle" :checked="ele.isCheckedAll"
                                :class="ele.isCheckedAll ? 'selectAc checkbox' : 'checkbox'" />
                        </view>
                    </u-checkbox-group>

                    <u-checkbox-group>
                        <view class="user_list">
                            <view class="user_item" @tap="clickUseItem(idx)" v-for="(item, idx) in ele.children" :key="idx">
                                <view :class="item.checked ? 'selectAc left_userinfo' : 'left_userinfo'">
                                    <view class="username">{{ item.name }} ({{ item.loginName }})</view>
                                    <view class="department">{{ ele.orgName }}</view>
                                </view>
                                <view class="right_checkbox">
                                    <u-checkbox @change="changeItem(idx, $event)" activeColor="#2362A6" shape="circle"
                                        :class="item.checked ? 'selectAc checkbox' : 'checkbox'" :checked="item.checked"
                                        :name="item.userId" />
                                </view>
                            </view>
                        </view>
                    </u-checkbox-group>
                </view>
            </scroll-view>
        </view>
        <view class="submit" :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }">
            <view class="resetBtn" @tap="handleReset">清空</view>
            <view class="confirm" @tap="handleconfirm">确定</view>
        </view>
    </view>
</template> 
  
<script setup lang="ts">
import { ref, reactive } from 'vue'
import { getWanderList, userList, issueAdduser,getissueHandlers } from '@/api/http'
import { onLoad, onUnload } from "@dcloudio/uni-app";
import modal from '@/plugins/modal';
const { safeAreaInsets } = uni.getSystemInfoSync()
const doc: any = ref([])
let copyVal = []
//type==1代表点击收文流转的流转按钮  
//type==4 代表点击收文阅办的流转按钮
//type==5代表是办学单位 公文接收的流转
const props = defineProps(['type', 'issueId', 'issueOneId'])

const para = ref({ pageNum: 1, pageSize: 10000, name: '', loginName: '' })
let acIndex = ref(0)

onLoad(() => {
    getList()
})
const searchCon = (e: string) => {
    para.value.name = e
    getList()
}
const handleReset = () => {
    uni.showModal({
        content: '确定清空?',
        showCancel: true,
        success: ({ confirm }) => {
            if (confirm) {
                reset()
            }
        }
    })
}
const changeItem = (idx: number, event: any) => {
    doc.value[acIndex.value].children[idx].checked = event
    changeStatus()
}
const getList = async () => {
    let res;
    uni.showLoading({title:'加载中'})
    if (props.type == 5) {
        res = await userList(para.value)
        copyVal = res.rows
    } else {
        res = await getWanderList(para.value)
        copyVal = res.rows
    }
    uni.hideLoading()
    let firesult = filterData(res.rows)
    firesult.forEach(ele => {
        ele.dataSorce = [];
        ele.isCheckedAll = false;
        if (ele.children && ele.children.length > 0) {
            ele.children.forEach(item => {
                item.checked = false
            })
        }
    })
    doc.value = firesult
}
const filterData = (arr: any) => {
    return arr.reduce((acc, item) => {
        // 在累计值中查找是否已存在当前orgName
        const found = acc.find(i => i.orgName === item.orgName);
        if (found) {
            // 如果已存在，那么在children数组中添加当前item（除了orgName属性）
            const { orgName, ...rest } = item;
            found.children.push({ ...rest, orgName });
        } else {
            // 如果没有找到，那么新建一个对象，并在children数组中添加当前item（除了orgName属性）
            const { orgName, ...rest } = item;
            acc.push({ orgName, children: [{...rest, orgName}] });
        }

        return acc;
    }, []);
}

const clickItem = (idx) => {
    acIndex.value = idx
}

const clickUseItem = (idx) => {
    let item = doc.value[acIndex.value].children[idx]
    doc.value[acIndex.value].children[idx].checked = !item.checked
    // 根据复选框的选中状态更新dataSorce数组
    changeStatus()
}
const changeStatus = () => {
    let len = doc.value[acIndex.value].children.length
    doc.value[acIndex.value].dataSorce = doc.value[acIndex.value].children
        .filter(child => child.checked)
        .map(child => child)
    // 单个选中 影响全选
    if (doc.value[acIndex.value].dataSorce.length == len) {
        doc.value[acIndex.value].isCheckedAll = true
    } else {
        doc.value[acIndex.value].isCheckedAll = false
    }
}
const handleCheckedAll = () => {
    let itemAll = doc.value[acIndex.value].children
    // 获取当前的全选状态
    let itemCheckAll = doc.value[acIndex.value].isCheckedAll
    if (!itemCheckAll) {
        // 全选 选中
        doc.value[acIndex.value].dataSorce = itemAll
    } else {
        // 全选取消 
        doc.value[acIndex.value].dataSorce = []
    }
    itemAll.forEach(ele => {
        ele.checked = !itemCheckAll
    })
    // 全选按钮也选中/取消
    doc.value[acIndex.value].isCheckedAll = !itemCheckAll

}

const reset = () => {
    doc.value.forEach(ele => {
        ele.dataSorce = [];
        ele.isCheckedAll = false
        if (ele.children && ele.children.length > 0) {
            ele.children.forEach(item => {
                item.checked = false
            })
        }
    })
}
const handleconfirm = async () => {
    let flag: any = []
    doc.value.forEach(ele => {
        if (ele.dataSorce.length > 0) {
            flag.push(...ele.dataSorce)
        }
    })
    if (flag.length == 0) return modal.showToast('请选择用户')
    // type如果是 false 说明是从 docToReadDetail过来的
    if (!props.type) {
        uni.$emit('propsUserA', flag)
    } else if (props.type == 5) {
        //公文接收  流转(添加人员)
        const userIds = flag.map(ele => ele.userId)
        const { issueId, issueOneId } = props
        const res = await issueAdduser({ userIds, issueId, issueOneId })
        uni.$emit('read')
        modal.msgSuccess('操作成功')
    } 
    
    // else {
    //     uni.$emit('propsUser', flag)
    // }

    uni.navigateBack({ delta: 1 })

}
</script>
  
<style lang="scss">
page {
    overflow: hidden;
    height: 100%;
    background-color: #fff;
}

.selectAc {
    .username {
        color: #2362A6 !important;
    }


    .wx-checkbox-input {
        border-color: #2362A6;
        background-color: #2362A6 !important;
    }
}



.checkbox .wx-checkbox-input {
    border-radius: 50%;
    width: 37rpx;
    height: 37rpx;
    background-color: #fff;

}

.checkbox .wx-checkbox-input.wx-checkbox-input-checked::before {
    color: #fff;
    font-size: 35rpx;
}



.wanderReceive {
    display: flex;
    flex-direction: column;
    height: 100%;


    .bottom_container {
        flex: 1;
        display: flex;
        height: 100%;
        overflow: hidden;

        .left_scroll {
            width: 240rpx;
            height: 100%;
            background-color: #f2f3f5;

            .scroll_item {
                position: relative;
                display: flex;
                align-items: center;
                padding: 10rpx 25rpx 10rpx 25rpx;
                color: #333;
                font-size: 28rpx;
                min-height: 100rpx;
                box-sizing: border-box;


                .line {
                    position: absolute;
                    top: 50%;
                    left: 0;
                    transform: translateY(-50%);
                    width: 10rpx;
                    height: 30rpx;
                    background-color: #2362A6;
                }
            }

            .clickAct {
                background-color: #fff;
                color: #2362A6;
            }
        }

        .right_scroll {
            flex: 1;
            height: 100%;
            // background-color: skyblue;

            .user_box {
                padding: 25rpx 24rpx 0;

                .checkAll {
                    width: 100%;
                    display: flex;
                    justify-content: space-between;

                    .text {
                        color: #333;
                        font-size: 28rpx;
                    }
                }

                .user_list {
                    margin-top: 20rpx;
                    width: 100%;

                    .user_item {
                        display: flex;
                        justify-content: space-between;
                        align-items: center;
                        font-size: 28rpx;
                        min-height: 110rpx;

                        .left_userinfo {
                            .username {
                                color: #333;
                                font-weight: 700;
                            }

                            .department {
                                color: #a2a2a2;
                                margin-top: 5rpx;
                            }
                        }
                    }
                }
            }

        }
    }

    .submit {
        display: flex;
        justify-content: space-around;
        align-items: center;
        height: 100rpx;
        background-color: #fff;

        .resetBtn,
        .confirm {
            width: 320rpx;
            height: 80rpx;
            border-radius: 40rpx;
            text-align: center;
            line-height: 80rpx;
            font-size: 28rpx;
            background-color: #e7e7e7;
        }

        .resetBtn {
            color: #333;

        }

        .confirm {
            color: #fff;
            background-color: #2362A6;
        }

    }
}
</style>
  